﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.IM/ImExtensions 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       ImExtensions
* 创建时间：  2025/5/23 16:37:00
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SSPivot.Common.Helpers;
using SSPivot.IM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// Im扩展
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Im
        /// </summary>
        /// <param name="services"></param>
        public static void AddImClient(this IServiceCollection services, IConfiguration configuration)
        {
            var config = configuration.GetSection("ImConfig").Get<ImConfig>();// ConfigHelper.Get<ImConfig>("ImConfig");
            if (!config.Enabled) return;

            ImHelper.Initialization(new ImClientOptions
            {
                Redis = new FreeRedis.RedisClient(config.RedisConnectionString),
                Servers = config.Servers,
            });

            ImHelper.Instance.OnSend += (s, e) =>
            {
                //Console.WriteLine($"ImClient.SendMessage(server={e.Server},data={JsonHelper.Serialize(e.Message)})");
            };

            ImHelper.EventBus(
                t =>
                {
                    //Console.WriteLine(t.clientId + "上线了");
                },
                t =>
                {
                    //Console.WriteLine(t.clientId + "下线了");
                }
            );

        }
        /// <summary>
        /// 添加im服务端
        /// </summary>
        /// <param name="builder"></param>
        public static void AddImServer(this IApplicationBuilder app, IConfiguration configuration)
        {
            var config = configuration.GetSection("ImConfig").Get<ImConfig>();// ConfigHelper.Get<ImConfig>("ImConfig");
            if (!config.Enabled) return;

            app.UseFreeImServer(new ImServerOptions
            {
                Redis = new FreeRedis.RedisClient(config.RedisConnectionString),
                Servers = config.Servers, //集群配置
                Server = config.Server
            }); 
        }
    }
}
